package com.playball.lottery.frm.buyhall;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.customview.ChildDTO;
import com.playball.lottery.customview.GroupDTO;
import com.playball.lottery.customview.MyDialog;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.ConvertJsonToList;
import com.playball.lottery.util.DateUtil;
import com.playball.lottery.util.DefConstants;
import com.playball.lottery.util.JclqHHMoneyForecastUtil;
import com.playball.lottery.util.LotConstants;


/*
 * 混合投注
 */
public class JclqHhtzDetail extends BaseActivity implements DefConstants {

	// private TextView buy_jclist_bs;
	// private TextView passTypeText;
	// private TextView countText;
	private TextView moneyText;
	private TextView tipText;
	private TextView tvMyuce;
	private EditText buy_jclist_bs;

	private TextView btnBuy;
	private Button btnChioce;
	/** 发起合买 */
	private TextView buy_jcbasxhlb_btn_hemai;
	private int bs = 1;// 倍数
	private long allMoney;// 总金额
	private long count; // 注数
	private String passType;
	private ArrayList<GroupDTO> datas;
	private String issueName;
	private static List<ChildDTO> caculateData;
	private ListView lv_bet;
	private HhtzDetailAdapter adapter;
	boolean[] selected = new boolean[] { false, false, false, false, false, false, false };
	// /** 2串1,3串1,4串1 */
	// boolean[] hhselected = new boolean[] { false, false, false };
	/** 最小奖金预测 */
	static BigDecimal bdminM = new BigDecimal("0");
	/** 最大奖金预测 */
	static BigDecimal bdmaxM = new BigDecimal("0");
	boolean hasSFC;

	private String[] dyn;

	private TextWatcher textWatcher = new TextWatcher() {
		private boolean isChanged = false;

		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			if (isChanged) {
				return;
			}
			if (!buy_jclist_bs.getText().toString().equals("")) {
				bs = Integer.parseInt(s.toString());
				isChanged = true;
				String str2 = s.toString().trim().replaceFirst("^0*", "");// 正则去除
				if (bs < 1) {
					Toast.makeText(JclqHhtzDetail.this, R.string.the_minimum_ratio_of_one, Toast.LENGTH_SHORT).show();
					buy_jclist_bs.setText("1");
					bs = 1;
				} else if (bs > 99999) {
					Toast.makeText(JclqHhtzDetail.this, R.string.the_maximum_ratio_of_nine_hundred_and_ninety_nine,
							Toast.LENGTH_SHORT).show();
					buy_jclist_bs.setText("99999");
					bs = 99999;
				} else {
					buy_jclist_bs.setText(str2);
				}
				buy_jclist_bs.setSelection(buy_jclist_bs.length());
				isChanged = false;
				buy_jclist_bs.invalidate();
				Long m = Long.parseLong(allMoney + "") * Integer.parseInt(buy_jclist_bs.getText().toString());
				// beishu.setText(buy_jclist_bs.getText().toString() + "");
				moneyText.setText("共" + m + "彩豆");
				// 保留小数点后2位,
				BigDecimal bdbs = new BigDecimal(bs + "");
				String f1 = bdbs.multiply(bdminM).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
				String f2 = bdbs.multiply(bdmaxM).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
				tvMyuce.setText(f1 + "彩豆-" + f2 + "彩豆");

			} else {
				buy_jclist_bs.setOnFocusChangeListener(new OnFocusChangeListener() {
					public void onFocusChange(View view, boolean hasFocus) {
						// TODO Auto-generated method stub
						if (hasFocus) {
							buy_jclist_bs.setText("");
						} else {
							if (buy_jclist_bs.getText().toString().equals("")) {
								Toast.makeText(JclqHhtzDetail.this, R.string.buy_at_least_one_times, Toast.LENGTH_SHORT)
										.show();
							}
						}
					}
				});
				bs = 0;
				moneyText.setText("共0彩豆");
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.hhtz_detail);
		Intent intent = getIntent();
		datas = (ArrayList<GroupDTO>) intent.getSerializableExtra("datas");
		issueName = intent.getStringExtra("IssueName");
		btnBuy = (TextView) findViewById(R.id.bottom_right_btn);
		btnChioce = (Button) findViewById(R.id.buy_jclist_chioce);
		buy_jcbasxhlb_btn_hemai = (TextView) findViewById(R.id.bottom_left_btn);
		// bsText = (TextView) findViewById(R.id.buy_jclist_bs);////相同ID
		moneyText = (TextView) findViewById(R.id.bottom_tv_money);
		tipText = (TextView) findViewById(R.id.buy_jclist_tip);
		tvMyuce = (TextView) findViewById(R.id.tv_win_ranger);
		lv_bet = (ListView) findViewById(R.id.hhtz_detail_list);
		buy_jclist_bs = (EditText) findViewById(R.id.buy_jclist_bs);// 相同ID
		buy_jclist_bs.addTextChangedListener(textWatcher);
		bs = 1;
		// buy_jclist_bs.setText("1");
		// countText.setText("0");
		moneyText.setText("共0彩豆");
		buy_jclist_bs.setText("1");
		titleBar();

		caculateData = new ArrayList<ChildDTO>();
		for (GroupDTO groupDTO : datas) {
			String wk = groupDTO.title.substring(0, 2);
			wk = DateUtil.getJCLQWKName(wk);
			for (ChildDTO childDTO : groupDTO.children) {
				if (!TextUtils.isEmpty(childDTO.hhtz1) || !TextUtils.isEmpty(childDTO.hhtz2)
						|| !TextUtils.isEmpty(childDTO.hhtz3) || !TextUtils.isEmpty(childDTO.hhtz4)) {
					childDTO.title = wk;
					caculateData.add(childDTO);
				}
			}
		}

		adapter = new HhtzDetailAdapter(caculateData, JclqHhtzDetail.this);
		lv_bet.setAdapter(adapter);

		/****************** 2014年6月17日14:53:56 **************************/
		int length;
		length = caculateData.size();
		hasSFC = false;
		for (ChildDTO cto : caculateData) {
			if (!TextUtils.isEmpty(cto.hhtz4)) {
				if (cto.hhtz4.length() >= 1) {
					hasSFC = true;
				}
			}
		}
		// 最多只有8串1
		if (length > 7) {
			length = 8;
		}
		// 如果是胜分差，最多只有4串1
		if (hasSFC) {
			if (length > 3) {
				length = 4;
			}
			if (length == 2) {
				selected[0] = true;
			} else if (length == 3) {
				selected[1] = true;
			} else if (length == 4) {
				selected[2] = true;
			} else {
				selected[2] = true;
			}
		} else {
			if (length == 2) {
				selected[0] = true;
			} else if (length == 3) {
				selected[1] = true;
			} else if (length == 4) {
				selected[2] = true;
			} else if (length == 5) {
				selected[3] = true;
			} else if (length == 6) {
				selected[4] = true;
			} else if (length == 7) {
				selected[5] = true;
			} else if (length == 8) {
				selected[6] = true;
			} else {
				selected[6] = true;
			}
		}

		String selectedStr = "";
		for (int i = 0; i < selected.length; i++) {
			if (selected[i] == true) {
				if (selectedStr.equals("")) {
					selectedStr = getResources().getStringArray(R.array.buy_jczq_hunhe)[i];
				} else {
					selectedStr = selectedStr + "," + getResources().getStringArray(R.array.buy_jczq_hunhe)[i];
				}
			}
		}
		passType = selectedStr.replace("串", "*");
		btnChioce.setText(selectedStr);
		allMoney = getMoney(caculateData);

		View.OnClickListener listener = new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				passType = "";
				Dialog dialog = null;
				String arr[] = getResources().getStringArray(R.array.buy_jczq_hunhe);
				int length;
				length = caculateData.size();
				hasSFC = false;
				for (ChildDTO cto : caculateData) {
					if (!TextUtils.isEmpty(cto.hhtz4)) {
						if (cto.hhtz4.length() >= 1) {
							hasSFC = true;
						}
					}
				}
				// 最多只有8串1
				if (length > 7) {
					length = 8;
				}
				// 如果是胜分差，最多只有4串1
				if (hasSFC) {
					if (length > 3) {
						length = 4;
					}
				}
				if (length <= 1) {
					Toast.makeText(JclqHhtzDetail.this, R.string.select_at_least_two, Toast.LENGTH_SHORT).show();
				} else {
					String pass[] = new String[length - 1];
					for (int i = 0; i < length - 1; i++) {
						pass[i] = arr[i];
					}
					Builder builder = new AlertDialog.Builder(JclqHhtzDetail.this);
					builder.setTitle(getString(R.string.buy_jclist_passtype));
					DialogInterface.OnMultiChoiceClickListener mutiListener = new DialogInterface.OnMultiChoiceClickListener() {
						@Override
						public void onClick(DialogInterface dialogInterface, int which, boolean isChecked) {
							selected[which] = isChecked;
						}
					};
					builder.setMultiChoiceItems(pass, selected, mutiListener);
					DialogInterface.OnClickListener btnListener = new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialogInterface, int which) {
							String selectedStr = "";
							for (int i = 0; i < selected.length; i++) {
								if (selected[i] == true) {
									if (selectedStr.equals("")) {
										selectedStr = getResources().getStringArray(R.array.buy_jczq_hunhe)[i];
									} else {
										selectedStr = selectedStr + ","
												+ getResources().getStringArray(R.array.buy_jczq_hunhe)[i];
									}
								}
							}
							passType = selectedStr.replace("串", "*");
							btnChioce.setText(selectedStr);
							allMoney = getMoney(caculateData);
						}
					};
					builder.setPositiveButton("确定", btnListener);
					dialog = builder.create();
					dialog.show();
				}

			}
		};
		btnChioce.setOnClickListener(listener);

		Collections.sort(caculateData, new SortByTime());
		tipText.setText("共" + caculateData.size() + "场比赛，截止时间：" + caculateData.get(0).geteTime());

		// 购买按钮
		btnBuy.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(bs * allMoney > 2000000){
					Toast.makeText(JclqHhtzDetail.this, "单个方案的总金额必须在2彩豆至2000000彩豆之间", Toast.LENGTH_SHORT).show();
					return;
				}
				if (caculateData.size() < 1) {
					Toast.makeText(JclqHhtzDetail.this, R.string.betting_accounts_cannot_be_empty, Toast.LENGTH_SHORT)
							.show();
				} else if (passType == null || passType.equals("")) {
					Toast.makeText(JclqHhtzDetail.this, R.string.select_a_pass_way, Toast.LENGTH_SHORT).show();
				} else if (buy_jclist_bs.getText().toString().equals("")) {
					Toast.makeText(JclqHhtzDetail.this, R.string.buy_at_least_one_times, Toast.LENGTH_SHORT).show();
					buy_jclist_bs.setText("1");
				} else {
					startBuyThread();

					/*
					 * MyDialog dialog = new
					 * MyDialog.Builder(JclqHhtzDetail.this
					 * ).setTitle("购买提示").setMessage("是否确认购买？")
					 * .setPositiveButton("确定", new
					 * DialogInterface.OnClickListener() { public void
					 * onClick(DialogInterface dialog, int which) { //
					 * startVouchersThread(); startBuyThread(); dialog.cancel();
					 * } }).setNegativeButton("取消", new
					 * DialogInterface.OnClickListener() {
					 * 
					 * @Override public void onClick(DialogInterface dialog, int
					 * which) { dialog.cancel(); } }).create();
					 * dialog.setCanceledOnTouchOutside(false);
					 * dialog.setCancelable(true);// 设置back键是否可以取消
					 * dialog.show();
					 */
				}
			}
		});

		// 发起合买
		buy_jcbasxhlb_btn_hemai.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if (caculateData.size() < 1) {
					Toast.makeText(JclqHhtzDetail.this, R.string.betting_accounts_cannot_be_empty, Toast.LENGTH_SHORT)
							.show();
				} else if (passType == null || passType.equals("")) {
					Toast.makeText(JclqHhtzDetail.this, R.string.select_a_pass_way, Toast.LENGTH_SHORT).show();
				} else if (buy_jclist_bs.getText().toString().equals("")
						|| Long.parseLong(buy_jclist_bs.getText().toString()) == 0) {
					Toast.makeText(JclqHhtzDetail.this, R.string.buy_at_least_one_times, Toast.LENGTH_SHORT).show();
					buy_jclist_bs.setText("1");
				} else {
					Intent intent = new Intent();
					String lotNum = getLotNum();
					intent.putExtra("list_jcdto", adapter.getDatas());
					if (moneyText.getText().toString() != null) {
						intent.putExtra("AllMoney", Integer.parseInt(allMoney + ""));
					} else {
						intent.putExtra("AllMoney", 0);
					}
					intent.putExtra("bs", bs);
					intent.putExtra("LotID", LOT_ID_JCLQ);
					intent.putExtra("IssueName", issueName);
					intent.putExtra("strLQWF", "HHTZ");
					intent.putExtra("passType", passType);
					intent.putExtra("Number", lotNum);
					// intent.putExtra("PlayTypeId", playTypeID);
					intent.setClass(JclqHhtzDetail.this, FaQiHeMaiActivity.class);
					JclqHhtzDetail.this.startActivityForResult(intent, REQ_CODE_BUYMAIN);
				}
			}
		});

	}

	public void onResume() {
		super.onResume();
		
	}

	public void onPause() {
		super.onPause();
		
	}

	private void startBuyThread() {
		String lotNum = getLotNum();

		AsyncLoader task = new AsyncLoader();
		dyn = new String[2];
		JSONObject params = new JSONObject();

		try {
			// 设置请求所需参数
			JSONObject params0 = new JSONObject();
			params0.put("playid", 9105);
			params0.put("number", lotNum);
			params.put("SchemeType", 1);// 方案类型 1自购，2合买，3保存 1
			params.put("BetType", 1);// 投注类型 1选号投注 2单式上传 3先发后传 1
			params.put("BonusScale", 0);
			params.put("AssureShare", 0);
			params.put("Description", "");
			params.put("OpenUserList", "");
			params.put("SecrecyLevel", 4);
			params.put("BuyShare", bs * allMoney);
			params.put("Multiple", bs);
			params.put("LotteryID", LotConstants.LOT_ID_JCLQ);
			params.put("IssueName", issueName);
			params.put("IssueID", "2016");//issueName
			params.put("Number", "[" + params0.toString() + "]");
			params.put("Money", bs * allMoney);
		} catch (JSONException ex) {
			// TODO Auto-generated catch block
			Log.e("error", ex.toString());
		}
		dyn[0] = params.toString();
		dyn[1] = "207";
		task.execute(dyn);
	}

	public String getLotNum() {
		String res = "";
		for (ChildDTO cto : caculateData) {
			res = res + cto.getmId() + "=";
			boolean bf = true;
			if (!TextUtils.isEmpty(cto.hhtz2)) {
				if (cto.hhtz2.length() >= 1) {
					res += "1_";
					bf = false;
					if (cto.hhtz2.contains("1")) {
						res += "1/";
					}
					if (cto.hhtz2.contains("2")) {
						res += "2/";
					}
					res = res.substring(0, res.length() - 1);
				}
			}
			if (!TextUtils.isEmpty(cto.hhtz1)) {
				if (cto.hhtz1.length() >= 1) {
					if (bf == false)
						res += "^2_";
					else {
						res += "2_";
						bf = false;
					}
					if (cto.hhtz1.contains("1")) {
						res += "1/";
					}
					if (cto.hhtz1.contains("2")) {
						res += "2/";
					}
					res = res.substring(0, res.length() - 1);
				}
			}
			if (!TextUtils.isEmpty(cto.hhtz4)) {
				if (cto.hhtz4.length() >= 1) {
					if (bf == false)
						res += "^3_";
					else {
						res += "3_";
						bf = false;
					}
					if (cto.hhtz4.contains("1")) {
						res += "11/";
					}
					if (cto.hhtz4.contains("2")) {
						res += "12/";
					}
					if (cto.hhtz4.contains("3")) {
						res += "13/";
					}
					if (cto.hhtz4.contains("4")) {
						res += "14/";
					}
					if (cto.hhtz4.contains("5")) {
						res += "15/";
					}
					if (cto.hhtz4.contains("6")) {
						res += "16/";
					}
					if (cto.hhtz4.contains("a")) {
						res += "01/";
					}
					if (cto.hhtz4.contains("b")) {
						res += "02/";
					}
					if (cto.hhtz4.contains("c")) {
						res += "03/";
					}
					if (cto.hhtz4.contains("d")) {
						res += "04/";
					}
					if (cto.hhtz4.contains("e")) {
						res += "05/";
					}
					if (cto.hhtz4.contains("f")) {
						res += "06/";
					}
					res = res.substring(0, res.length() - 1);
				}
			}
			if (!TextUtils.isEmpty(cto.hhtz3)) {
				if (cto.hhtz3.length() >= 1) {
					if (bf == false)
						res += "^4_";
					else {
						res += "4_";
						bf = false;
					}
					if (cto.hhtz3.contains("1")) {
						res += "1/";
					}
					if (cto.hhtz3.contains("2")) {
						res += "2/";
					}
					res = res.substring(0, res.length() - 1);
				}
			}
			res = res + ",";
		}
		res = res.substring(0, res.length() - 1);
		res = res + "|" + passType + "|0";
		// System.out.println(res);
		return res;
	}

	/**
	 * 初始化奖金预测值
	 */
	public static void initMoney() {
		bdminM = new BigDecimal("0");
		bdmaxM = new BigDecimal("0");
		// Log.e("xhlb initMoney ", "bdminM= "+bdminM.toString());
		// Log.e("xhlb initMoney", "bdmaxM= "+bdmaxM.toString());
	}

	// 获取金额
	public long getMoney(List<ChildDTO> arrayList) {

		// 当用户重新选择几串一时，初始化值
		bdminM = new BigDecimal("0");
		bdmaxM = new BigDecimal("0");
		count = 0;
		String[] types = passType.split(",");
		// System.out.println("types.length:" + types.length);
		boolean isFirst = true;
		for (int i = 0; i < types.length; i++) {
			String type = types[i];
			// 进行计算所需的参数
			int num = getNumByPassType(type);
			if (num != 0) {
				String result = JclqHHMoneyForecastUtil.getMatchCount(num, arrayList);
				count += Long.parseLong(result.split("\\|")[0]);
				// 最小奖金
				BigDecimal bdTWO = new BigDecimal("2");
				BigDecimal bdmintemp = new BigDecimal(result.split("\\|")[1]);
				BigDecimal bdtemp = bdTWO.multiply(bdmintemp);
				if (isFirst) {
					BigDecimal bdmin0 = new BigDecimal(result.split("\\|")[1]);
					bdminM = bdTWO.multiply(bdmin0);
					isFirst = false;
				}
				if (bdtemp.compareTo(bdminM) == -1 || bdtemp.compareTo(bdminM) == 0) {
					bdminM = bdtemp;
				}
				// 最大奖金
				BigDecimal bdmax0 = new BigDecimal(result.split("\\|")[2]);
				bdmaxM = bdmaxM.add(bdTWO.multiply(bdmax0));
			}
		}
		// System.out.println("count:" + count);
		// countText.setText(count + "");
		moneyText.setText("共" + (Long.parseLong((count * 2) * bs + "") + "") + "彩豆");
		// 保留小数点后2位,
		BigDecimal bdbs = new BigDecimal(bs + "");
		String f1 = bdbs.multiply(bdminM).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
		String f2 = bdbs.multiply(bdmaxM).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
		tvMyuce.setText(f1 + "彩豆-" + f2 + "彩豆");
		return count * 2;
	}

	// 根据过关方式获取计算阶乘时所需参数,混合过关最多只有4串1
	public int getNumByPassType(String type) {
		int num = 0;
		if (type.equals("2*1")) {
			num = 2;
		}
		if (type.equals("3*1")) {
			num = 3;
		}
		if (type.equals("4*1")) {
			num = 4;
		}
		if (type.equals("5*1")) {
			num = 5;
		}
		if (type.equals("6*1")) {
			num = 6;
		}
		if (type.equals("7*1")) {
			num = 7;
		}
		if (type.equals("8*1")) {
			num = 8;
		}
		return num;
	}

	public void clearWarning() {
		if (caculateData.size() >= 1) {
			MyDialog.Builder dialog = new MyDialog.Builder(JclqHhtzDetail.this);
			dialog.setTitle("退出提示");
			dialog.setMessage("退出后您的投注将不会保存，确认继续?");
			dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// 获得自定义的应用程序BallDTO,初始化
					// app_jcdto.initList();
					JcBasketballActivity.clearHhtzSel();
					initMoney();
					setResult(RESULT_OK);
					JclqHhtzDetail.this.finish();
				}
			});
			dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			}).create().show();
		} else {
			JcBasketballActivity.clearHhtzSel();
			initMoney();
			setResult(RESULT_OK);
			JclqHhtzDetail.this.finish();
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK) {
			if (requestCode == REQ_CODE_BUYMAIN || requestCode == REQ_CODE_NO_MONEY_2_RECHARGE) {
				ApplicationData.getInstance().resetJCData();
				setResult(110);
				finish();
			}
		}
	};

	// titleBar标题栏
	public void titleBar() {
		// Title信息(返回+Title)
		Button back = (Button) findViewById(R.id.top_title_back);
		back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
		back.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				clearWarning();
			}
		});

		TextView info = (TextView) findViewById(R.id.top_title_info);
		info.setText("竞彩篮球(混合过关)");
		Button refres = (Button) findViewById(R.id.top_title_refres);
		refres.getBackground().setAlpha(255);
		refres.setVisibility(View.INVISIBLE);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			clearWarning();
		} else {
			return super.onKeyDown(keyCode, event);
		}
		return true;
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
	};

	// 按时间来排序
	class SortByTime implements Comparator<ChildDTO> {
		@Override
		public int compare(ChildDTO lhs, ChildDTO rhs) {
			// TODO Auto-generated method stub
			ChildDTO s1 = (ChildDTO) lhs;
			ChildDTO s2 = (ChildDTO) rhs;
			Long a = Long.parseLong(getDateTime(s1.eTime));
			Long b = Long.parseLong(getDateTime(s2.eTime));
			return a.compareTo(b);
		}

		public String getDateTime(String b) {
			java.util.Date d = null;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				d = sdf.parse(b);
			} catch (ParseException pe) {
				// System.out.println(pe.getMessage());
			}
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
			String date = sdf1.format(d);
			return date + "";
		}
	}

	public void Buy(String strResult) {
		try {
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			int buy_icon = 0;
			if (Integer.parseInt(js.getString("Code")) < 0) {
				buy_icon = R.drawable.buy_failure;

				// System.out.println("购买失败");
				new ShowTipDialog().showBuyInfo(JclqHhtzDetail.this, js.getString("Data"), "购买失败", buy_icon, dyn[0]);
			} else {
				buy_icon = R.drawable.buy_success;

				String msg = "发起竞彩篮球购买方案\n\n我的认购：" + (bs * allMoney/*
																	 * -
																	 * canDeductMoney
																	 */)/* + "彩豆\n账户余额："
						+ ConvertJsonToList.getMap(js.getString("Data")).get("Balance").toString()/*
																								 * getBalance
																								 * (
																								 * )
																								 */+ "彩豆"+"\n方案编号："+js.getString("Data").toString();
				new ShowTipDialog().showBuyInfo(JclqHhtzDetail.this, msg, "投注成功", buy_icon, dyn[0]);
				// System.out.println(msg);
			}
		} catch (JSONException ex) {
			// 异常处理代码
			Log.e("error", ex.toString());
		}
	}

	public String getBalance() {
		String money = "";
		String strResult = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 设置请求所需参数
			JSONObject params = new JSONObject();
			// 设置请求action
			String action = "107";// 108获取用户基本信息
			// 获取请求返回值
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(params.toString(), UserID, action,
					getApplicationContext());
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			map = ConvertJsonToList.getMap(js.getString("Data"));
			// money =
			// Float.parseFloat(map.get("Balance").toString().replaceAll(",",
			// "").trim());
			money = map.get("Balance").toString();
		} catch (Exception ex) {
			// TODO Auto-generated catch block
			Log.e("error", ex.toString());
		}
		return money;
	}

	class AsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask

		String action;
		ShowTipDialog showdialog = new ShowTipDialog();

		// 1.准备运行
		protected void onPreExecute() {
			showdialog.showDialog(JclqHhtzDetail.this);
		}

		// 2.正在后台运行
		@Override
		protected String doInBackground(String... paramsArr) {
			// 处理后台执行的任务，在后台线程执行
			String strResult = null;

			action = paramsArr[1];
			// 获取请求返回值
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(paramsArr[0], UserID, action, getApplicationContext());
			// 获取请求返回值
			return strResult;
		}

		// 3.进度更新
		protected void onProgressUpdate(Integer... progress) {
		}

		// 4.完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {
				if (action.equals("207")) {
					Buy(result);
				}
				showdialog.closeDialog();
			} else {
				Toast.makeText(JclqHhtzDetail.this, getString(R.string.problem_01), Toast.LENGTH_LONG).show();
			}
		}

		// 5.完成后操作
		protected void onCancelled() {
		}

	}

	class HhtzDetailAdapter extends BaseAdapter {

		List<ChildDTO> data;
		LayoutInflater inflater;

		public HhtzDetailAdapter(List<ChildDTO> data, Context c) {
			this.data = data;
			inflater = (LayoutInflater) c.getSystemService(LAYOUT_INFLATER_SERVICE);
		}

		public ArrayList<ChildDTO> getDatas() {
			return (ArrayList<ChildDTO>) data;
		}

		public void delOne(int id) {
			// System.out.println("now del:" + id);
			data.remove(id);
			if (caculateData.size() == 0) {
				tipText.setText("共0场比赛，截止时间：------------");
			} else {
				tipText.setText("共" + caculateData.size() + "场比赛，截止时间：" + caculateData.get(0).geteTime());
			}
			notifyDataSetChanged();
		}

		public void delAll() {
			data.clear();
			if (caculateData.size() == 0) {
				tipText.setText("共0场比赛，截止时间：------------");
			} else {
				tipText.setText("共" + caculateData.size() + "场比赛，截止时间：" + caculateData.get(0).geteTime());
			}
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(final int arg0, View convertView, ViewGroup arg2) {
			// TODO Auto-generated method stub
			Holder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.hhtz_detail_item, null);
				holder = new Holder();
				holder.tv = (TextView) convertView.findViewById(R.id.hhtz_detail_item_bet);
				holder.btn = (Button) convertView.findViewById(R.id.hhtz_detail_item_del);
				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}
			ChildDTO childDTO = this.data.get(arg0);
			if (childDTO != null) {
				// 根据模型值设置textview的文本
				StringBuffer sb = new StringBuffer();
				sb.append("<hr>" + "<font color='#e3510a'>" + childDTO.title + (childDTO.mId).substring(6)
						+ "</font><font size='10dip' color='#0163bf'>  " + "\n" + childDTO.vTeam + " VS "
						+ childDTO.hTeam + "</font>");
				if (!TextUtils.isEmpty(childDTO.hhtz1)) {
					if (childDTO.hhtz1.length() >= 1) {
						sb.append("<br><font color='#0163bf'>胜负:</font><font color='#4c1d01'>");
						if (childDTO.hhtz1.contains("1")) {
							sb.append("主胜 ");
						}
						if (childDTO.hhtz1.contains("2")) {
							sb.append("主负 ");
						}
						sb.append("</font>");
					}
				}
				if (!TextUtils.isEmpty(childDTO.hhtz2)) {
					if (childDTO.hhtz2.length() >= 1) {
						sb.append("<br><font color='#0163bf'>让分胜负:</font><font color='#4c1d01'>");
						if (childDTO.hhtz2.contains("1")) {
							sb.append("主胜 ");
						}
						if (childDTO.hhtz2.contains("2")) {
							sb.append("主负 ");
						}
						sb.append("</font>");
					}
				}
				if (!TextUtils.isEmpty(childDTO.hhtz3)) {
					if (childDTO.hhtz3.length() >= 1) {
						sb.append("<br><font color='#0163bf'>大小分:</font><font color='#4c1d01'>");
						if (childDTO.hhtz3.contains("1")) {
							sb.append("大分 ");
						}
						if (childDTO.hhtz3.contains("2")) {
							sb.append("小分 ");
						}
						sb.append("</font>");
					}
				}
				if (!TextUtils.isEmpty(childDTO.hhtz4)) {
					if (childDTO.hhtz4.length() >= 1) {
						hasSFC = true;
						sb.append("<br><font color='#0163bf'>胜分差:</font><font color='#4c1d01'>");
						String tem = "";
						if (childDTO.hhtz4.contains("1")) {
							sb.append("客胜(1-5)  ");
						}
						if (childDTO.hhtz4.contains("2")) {
							sb.append("客胜(6-10)  ");
						}
						if (childDTO.hhtz4.contains("3")) {
							sb.append("客胜(11-15)  ");
						}
						if (childDTO.hhtz4.contains("4")) {
							sb.append("客胜(16-20)  ");
						}
						if (childDTO.hhtz4.contains("5")) {
							sb.append("客胜(21-25)  ");
						}
						if (childDTO.hhtz4.contains("6")) {
							sb.append("客胜其他  ");
						}
						if (childDTO.hhtz4.contains("a")) {
							sb.append("主胜(1-5)  ");
						}
						if (childDTO.hhtz4.contains("b")) {
							sb.append("主胜(6-10)  ");
						}
						if (childDTO.hhtz4.contains("c")) {
							sb.append("主胜(11-15)  ");
						}
						if (childDTO.hhtz4.contains("d")) {
							sb.append("主胜(16-20)  ");
						}
						if (childDTO.hhtz4.contains("e")) {
							sb.append("主胜(21-25)  ");
						}
						if (childDTO.hhtz4.contains("f")) {
							sb.append("主胜其他  ");
						}
						sb.append(tem + "</font>");
					}
				}
				holder.tv.setText(Html.fromHtml(sb.toString()));
				holder.btn.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// System.out.println("call del:" + arg0);

						if (data.size() > 2) {
							delOne(arg0);
							// 删除一场赛事后清空
							initMoney();
							bs = 1;
							passType = "";
							allMoney = 0;
							btnChioce.setText("请选择过关方式");
							selected = new boolean[] { false, false, false, false, false, false, false };
							buy_jclist_bs.setText("1");
							// countText.setText("0");
							moneyText.setText("共0彩豆");
							// passTypeText.setText("");
							tvMyuce.setText("0");
							passType = "";
						} else {
							Toast.makeText(JclqHhtzDetail.this, R.string.select_at_least_two, Toast.LENGTH_SHORT)
									.show();
						}
					}
				});
			}

			return convertView;
		}

		class Holder {
			TextView tv;
			Button btn;
		}
	}

}
